import { reqAddOrUpdateShoppingCart, reqDeleteShoppingCartAllChecked, reqDeleteShoppingCartOne, reqShoppingCartList, reqUpdateShoppingCartCheckedAll, reqUpdateShoppingCartCheckedOne } from '@/api'

const state = {
    //购物车列表
    shopCartList: []
}
const mutations = {
    //更新购物车列表
    RECEIVE_SHOPCARTLIST(state, shopCartList) {
        state.shopCartList = shopCartList
    }
}
const actions = {
    //添加或更新购物车
    async addOrUpdateShoppingCart({ commit }, { skuId, skuNum }) {
        const result = await reqAddOrUpdateShoppingCart(skuId, skuNum)
        if (result.code === 200) return 'succeed'
        else return new Promise.reject(new Error('failed'))
    },

    //获取购物车列表
    async getShopCartList({ commit }) {
        const result = await reqShoppingCartList()
        if (result.code === 200) {
            commit('RECEIVE_SHOPCARTLIST', result.data)
        }
    },

    //修改购物车选中状态
    async updateShoppingCartCheckedOne({ commit }, { skuId, isChecked }) {
        const result = await reqUpdateShoppingCartCheckedOne(skuId, isChecked)
        if (result.code === 200) return 'succeed'
        else return Promise.reject(new Error('失败'))
    },

    //批量修改购物车选中状态
    async reqUpdateShoppingCartCheckedAll({commit},{isChecked,skuIds}) {
        const result = await reqUpdateShoppingCartCheckedAll(isChecked,skuIds)
        if(result.code ===200) return 'succeed'
        else return Promise.reject(new Error('失败'))
    },

    //删除一个商品
    async deleteShoppingCartOne({commit},skuId){
        const result =await reqDeleteShoppingCartOne(skuId)
        if(result.code===200) return 'succeed'
        else return Promise.reject(new Error('失败'))
    },
    
    //删除所有选中的商品
    async deleteShoppingCartAllChecked({commit},skuIds){
        const result =await reqDeleteShoppingCartAllChecked(skuIds)
        if(result.code===200) return 'succeed'
        else return Promise.reject(new Error('失败'))
    }
}
const getters = {

}

export default {
    state,
    mutations,
    actions,
    getters,
}